package org.hgvc.webapp.ets.jsf.beans;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import javax.faces.context.FacesContext;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.jocsb.base.AbstractBean;
import org.jocsb.base.util.FacesUtils;

public class ReportBean extends AbstractBean {
	public static final String BEAN_NAME="reportBean";
	
	public void createReport(HashMap parameters,List list, String filename){

		try{

			StringBuffer pdfName = new StringBuffer(100);
			pdfName.append(filename+".pdf");

			StringBuffer jasperName = new StringBuffer(100);
			jasperName.append(filename+".jrxml");

			FacesContext ctx=FacesContext.getCurrentInstance();

			getResponse().setContentType("application/pdf");
			getResponse().addHeader("Content-Disposition", "attachment; filename="+pdfName.toString());

			InputStream is = FacesUtils.getServletContext().getResourceAsStream(File.separator+"WEB-INF"+File.separator+"reports"+File.separator+jasperName.toString());
			JasperDesign jasperDesign=JRXmlLoader.load(is);

			JasperReport jasperReport=JasperCompileManager.compileReport(jasperDesign);
			JRBeanCollectionDataSource dataSource=new JRBeanCollectionDataSource(list);

			JasperPrint jasperPrint=JasperFillManager.fillReport(jasperReport, parameters,dataSource);

			JasperExportManager.exportReportToPdfStream(jasperPrint, getResponse().getOutputStream());

			ctx.getApplication().getStateManager().saveSerializedView(ctx); 
			ctx.responseComplete();

		}catch(Exception ex){
			ex.printStackTrace();
		}	
	}
	
	public void createReportJasper(HashMap parameters,List list, String filename){
		
		try{
			StringBuffer pdfName = new StringBuffer();
			pdfName.append(filename+".pdf");

			StringBuffer jasperName = new StringBuffer();
			jasperName.append(filename+".jasper");

			FacesContext ctx=FacesContext.getCurrentInstance();

			getResponse().setContentType("application/pdf");
			getResponse().addHeader("Content-Disposition", "attachment; filename="+pdfName.toString());

			JRBeanCollectionDataSource dataSource=new JRBeanCollectionDataSource(list);

			JasperPrint jasperPrint=JasperFillManager.fillReport(getServletContext().getRealPath(File.separator+"WEB-INF"+File.separator+"reports"+File.separator+jasperName.toString()), parameters,dataSource);
			
			JasperExportManager.exportReportToPdfStream(jasperPrint, getResponse().getOutputStream());
			
			ctx.getApplication().getStateManager().saveSerializedView(ctx); 
			ctx.responseComplete();
			

		}catch(Exception e){
			e.printStackTrace();
		}	
	}
}
